package main

import (
	ex "justweb/internal"
	justWeb "justweb/pkg"
)

func main() {
	shutdown := justWeb.NewServerShutdown()
	adminSrv := justWeb.NewServer("adminSrv", justWeb.MetricFilterBuilder,
		shutdown.ShutdownFilterBuilder)
	srv := justWeb.NewServer("server", justWeb.MetricFilterBuilder,
		shutdown.ShutdownFilterBuilder)
	static := justWeb.NewStaticHandler("static", "/static", justWeb.WithFileCache(1<<20, 100))

	srv.Route("GET", "/hello", ex.Hello, "sayhello")
	srv.Route("GET", "/hello4", ex.Hello4)
	srv.Route("GET", "/hello/*", ex.Hello)
	srv.Route("GET", "/hello/:fff", ex.Hello2)
	srv.Route("GET", "/hello2/:fff", ex.Hello2)
	srv.Route("GET", "/hello3/:reg([1,9]+)", ex.Hello3)
	srv.Route("GET", "/signUp", ex.SignUp)
	srv.Route("GET", "/static/*", static.ServeStaticResource)
	// srv.Route("GET", "/lookTheRoute", ex.TheTreeNode)

	adminSrv.Route("GET", "/hello", ex.Hello)
	adminSrv.Route("GET", "/slow", ex.SlowService) // 超时服务

	// ex.UseServer(adminSrv)

	go func() {
		if err := adminSrv.Start(":8999"); err != nil {
			panic(err)
		}
	}()

	go func() {
		if err := srv.Start(":8899"); err != nil {
			panic(err)
		}
	}()

	// 监听关停信号并调度处理
	justWeb.WaitForShutdown(
		justWeb.NotifyThegateaway,              // 如果收到信号，先通知网关
		shutdown.RejectReqAndWait,              // 拒绝请求 - 关闭开始
		justWeb.CloseServerHook(srv, adminSrv), // 关闭过程
		justWeb.AfterShutdown,                  // 关闭之后 -- 清理临时资源之类的
	)
}

// 使用http自带的优雅关停
// func main() {
// 	sdk := justWeb.NewServer("web1", justWeb.MetricFilterBuilder)
// 	sdk.Route("GET", "/hello", ex.Hello, "sayhello")

// 	srv := &http.Server{ Addr: ":8888", Handler: sdk }
// 	go func() {
// 		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
// 			log.Fatalf("listen: %s\n", err)
// 		}
// 	}()

// 	// 等待关闭信号 -- 5秒的超时时间
// 	quit := make(chan os.Signal, 1)
// 	// kill (no param) default send syscall.SIGTERM
// 	// kill -2 是 syscall.SIGINT
// 	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
// 	<-quit
// 	log.Println("Shutting down server...")

// 	// The context is used to inform the server it has 5 seconds to finish
// 	// the request it is currently handling
// 	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
// 	defer cancel()
// 	if err := srv.Shutdown(ctx); err != nil {
// 		log.Fatal("Server forced to shutdown:", err)
// 	}

// 	log.Println("Server exiting")
// }
